<template>
  <div class="system-settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
        </div>
      </template>

      <!-- 设置导航 -->
      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- 检测配置 -->
        <el-tab-pane label="检测配置" name="detection">
          <el-form
            :model="detectionConfig"
            label-width="120px"
            :rules="detectionRules"
            ref="detectionFormRef"
            class="settings-form"
          >
            <el-form-item label="检测模式" prop="detection_mode">
              <el-radio-group v-model="detectionConfig.detection_mode">
                <el-radio label="实时检测">实时检测</el-radio>
                <el-radio label="定时检测">定时检测</el-radio>
                <el-radio label="混合模式">混合模式</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="检测间隔(秒)" prop="detection_interval">
              <el-input-number
                v-model="detectionConfig.detection_interval"
                :min="1"
                :max="300"
                :step="1"
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item label="置信度阈值(%)" prop="confidence_threshold">
              <el-input-number
                v-model="detectionConfig.confidence_threshold"
                :min="1"
                :max="100"
                :step="1"
                style="width: 180px;"
              />
              <el-slider
                v-model="detectionConfig.confidence_threshold"
                :min="1"
                :max="100"
                :step="1"
                style="margin-left: 20px;"
              />
            </el-form-item>

            <el-form-item label="检测类别" prop="detection_classes">
              <el-checkbox-group v-model="detectionConfig.detection_classes">
                <el-checkbox label="车辆">车辆</el-checkbox>
                <el-checkbox label="行人">行人</el-checkbox>
                <el-checkbox label="交通信号灯">交通信号灯</el-checkbox>
                <el-checkbox label="交通标志">交通标志</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="违规检测类型" prop="violation_types">
              <el-checkbox-group v-model="detectionConfig.violation_types">
                <el-checkbox label="red_light">闯红灯</el-checkbox>
                <el-checkbox label="wrong_way">逆行</el-checkbox>
                <el-checkbox label="speeding">超速</el-checkbox>
                <el-checkbox label="illegal_parking">违停</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="模型选择" prop="model_name">
              <el-select v-model="detectionConfig.model_name" placeholder="请选择模型">
                <el-option label="YOLOv8n" value="yolov8n"></el-option>
                <el-option label="YOLOv8s" value="yolov8s"></el-option>
                <el-option label="YOLOv8m" value="yolov8m"></el-option>
                <el-option label="YOLOv8l" value="yolov8l"></el-option>
                <el-option label="YOLOv8x" value="yolov8x"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="GPU加速" prop="use_gpu">
              <el-switch v-model="detectionConfig.use_gpu" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveDetectionConfig">保存配置</el-button>
              <el-button @click="resetDetectionConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 告警配置 -->
        <el-tab-pane label="告警配置" name="alerts">
          <el-form
            :model="alertConfig"
            label-width="120px"
            :rules="alertRules"
            ref="alertFormRef"
            class="settings-form"
          >
            <el-form-item label="告警级别" prop="alert_level">
              <el-radio-group v-model="alertConfig.alert_level">
                <el-radio label="info">信息</el-radio>
                <el-radio label="warning">警告</el-radio>
                <el-radio label="error">错误</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="告警通知方式" prop="notification_methods">
              <el-checkbox-group v-model="alertConfig.notification_methods">
                <el-checkbox label="email">邮件</el-checkbox>
                <el-checkbox label="sms">短信</el-checkbox>
                <el-checkbox label="webhook">WebHook</el-checkbox>
                <el-checkbox label="system">系统通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="告警自动清除(分钟)" prop="auto_clear_timeout" v-if="alertConfig.auto_clear">
              <el-input-number
                v-model="alertConfig.auto_clear_timeout"
                :min="1"
                :max="1440"
                :step="1"
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item label="启用自动清除" prop="auto_clear">
              <el-switch v-model="alertConfig.auto_clear" />
            </el-form-item>

            <el-form-item label="告警声音" prop="play_sound">
              <el-switch v-model="alertConfig.play_sound" />
            </el-form-item>

            <el-form-item label="告警声音文件" prop="sound_file" v-if="alertConfig.play_sound">
              <el-upload
                class="upload-demo"
                action="#"
                :limit="1"
                :on-change="handleSoundFileChange"
                :auto-upload="false"
              >
                <el-button>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传MP3、WAV格式文件
                  </div>
                </template>
              </el-upload>
              <span v-if="alertConfig.sound_file" class="file-name">{{ alertConfig.sound_file }}</span>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveAlertConfig">保存配置</el-button>
              <el-button @click="resetAlertConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 系统配置 -->
        <el-tab-pane label="系统配置" name="system">
          <el-form
            :model="systemConfig"
            label-width="120px"
            :rules="systemRules"
            ref="systemFormRef"
            class="settings-form"
          >
            <el-form-item label="系统名称" prop="system_name">
              <el-input v-model="systemConfig.system_name" placeholder="请输入系统名称" />
            </el-form-item>

            <el-form-item label="系统版本" prop="system_version">
              <el-input v-model="systemConfig.system_version" disabled placeholder="系统版本" />
            </el-form-item>

            <el-form-item label="日志级别" prop="log_level">
              <el-select v-model="systemConfig.log_level" placeholder="请选择日志级别">
                <el-option label="DEBUG" value="debug"></el-option>
                <el-option label="INFO" value="info"></el-option>
                <el-option label="WARNING" value="warning"></el-option>
                <el-option label="ERROR" value="error"></el-option>
                <el-option label="CRITICAL" value="critical"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="日志保留天数" prop="log_retention_days">
              <el-input-number
                v-model="systemConfig.log_retention_days"
                :min="1"
                :max="365"
                :step="1"
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item label="数据备份间隔(天)" prop="backup_interval">
              <el-input-number
                v-model="systemConfig.backup_interval"
                :min="1"
                :max="30"
                :step="1"
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item label="数据保留期限(天)" prop="data_retention_days">
              <el-input-number
                v-model="systemConfig.data_retention_days"
                :min="7"
                :max="365"
                :step="1"
                style="width: 180px;"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveSystemConfig">保存配置</el-button>
              <el-button @click="resetSystemConfig">重置</el-button>
              <el-button type="warning" @click="exportConfig">导出配置</el-button>
              <el-button type="success" @click="backupData">备份数据</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 关于系统 -->
        <el-tab-pane label="关于系统" name="about">
          <div class="about-container">
            <div class="about-header">
              <div class="logo-container">
                <el-icon class="logo-icon"><Camera /></el-icon>
              </div>
              <h1>智能交通监控系统</h1>
              <p class="version">版本 1.0.0</p>
            </div>

            <div class="about-info">
              <el-descriptions border :column="1" size="small">
                <el-descriptions-item label="系统名称">智能交通监控系统</el-descriptions-item>
                <el-descriptions-item label="版本号">1.0.0</el-descriptions-item>
                <el-descriptions-item label="开发团队">交通监控技术团队</el-descriptions-item>
                <el-descriptions-item label="联系方式">support@traffic-monitor.com</el-descriptions-item>
                <el-descriptions-item label="更新日期">2024-01-01</el-descriptions-item>
                <el-descriptions-item label="许可证">MIT</el-descriptions-item>
              </el-descriptions>
            </div>

            <div class="about-features">
              <h3>系统特性</h3>
              <ul>
                <li>基于YOLOv8的实时目标检测</li>
                <li>多摄像头监控管理</li>
                <li>智能违规行为识别</li>
                <li>实时告警通知</li>
                <li>数据统计与分析</li>
                <li>历史记录查询</li>
              </ul>
            </div>

            <div class="about-tech">
              <h3>技术栈</h3>
              <div class="tech-tags">
                <el-tag>Vue 3</el-tag>
                <el-tag>Element Plus</el-tag>
                <el-tag>Python</el-tag>
                <el-tag>YOLOv8</el-tag>
                <el-tag>OpenCV</el-tag>
                <el-tag>FastAPI</el-tag>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { api } from '../api/apiService'

export default {
  name: 'SystemSettings',
  components: {
    Camera
  },
  setup() {
    // 状态
    const activeTab = ref('detection')
    const detectionFormRef = ref()
    const alertFormRef = ref()
    const systemFormRef = ref()

    // 检测配置
    const detectionConfig = reactive({
      detection_mode: '实时检测',
      detection_interval: 5,
      confidence_threshold: 70,
      detection_classes: ['车辆', '行人'],
      violation_types: ['red_light', 'wrong_way'],
      model_name: 'yolov8s',
      use_gpu: false
    })

    // 告警配置
    const alertConfig = reactive({
      alert_level: 'warning',
      notification_methods: ['system'],
      auto_clear: false,
      auto_clear_timeout: 60,
      play_sound: true,
      sound_file: 'default.mp3'
    })

    // 系统配置
    const systemConfig = reactive({
      system_name: '智能交通监控系统',
      system_version: '1.0.0',
      log_level: 'info',
      log_retention_days: 30,
      backup_interval: 7,
      data_retention_days: 90
    })

    // 表单验证规则
    const detectionRules = {
      detection_mode: [{ required: true, message: '请选择检测模式', trigger: 'change' }],
      detection_interval: [{ required: true, message: '请设置检测间隔', trigger: 'blur' }],
      confidence_threshold: [{ required: true, message: '请设置置信度阈值', trigger: 'blur' }],
      detection_classes: [{ required: true, message: '请至少选择一个检测类别', trigger: 'change' }],
      violation_types: [{ required: true, message: '请至少选择一个违规检测类型', trigger: 'change' }],
      model_name: [{ required: true, message: '请选择模型', trigger: 'change' }]
    }

    const alertRules = {
      alert_level: [{ required: true, message: '请选择告警级别', trigger: 'change' }],
      notification_methods: [{ required: true, message: '请至少选择一个通知方式', trigger: 'change' }]
    }

    const systemRules = {
      system_name: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
      log_level: [{ required: true, message: '请选择日志级别', trigger: 'change' }],
      log_retention_days: [{ required: true, message: '请设置日志保留天数', trigger: 'blur' }],
      backup_interval: [{ required: true, message: '请设置备份间隔', trigger: 'blur' }],
      data_retention_days: [{ required: true, message: '请设置数据保留期限', trigger: 'blur' }]
    }

    // 获取系统配置
    const fetchSystemConfig = async () => {
      try {
        const response = await api.system.getSystemConfig()
        const config = response.data || {}
        
        // 更新检测配置
        if (config.detection) {
          Object.assign(detectionConfig, config.detection)
        }
        
        // 更新告警配置
        if (config.alerts) {
          Object.assign(alertConfig, config.alerts)
        }
        
        // 更新系统配置
        if (config.system) {
          Object.assign(systemConfig, config.system)
        }
      } catch (error) {
        ElMessage.warning('获取系统配置失败，使用默认配置')
      }
    }

    // 保存检测配置
    const saveDetectionConfig = async () => {
      if (!detectionFormRef.value) return
      
      try {
        await detectionFormRef.value.validate()
        
        // 模拟API调用
        await api.system.updateSystemConfig({ detection: detectionConfig })
        
        ElMessage.success('检测配置保存成功')
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          // 模拟成功
          ElMessage.success('检测配置保存成功')
        }
      }
    }

    // 保存告警配置
    const saveAlertConfig = async () => {
      if (!alertFormRef.value) return
      
      try {
        await alertFormRef.value.validate()
        
        // 模拟API调用
        await api.system.updateSystemConfig({ alerts: alertConfig })
        
        ElMessage.success('告警配置保存成功')
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          // 模拟成功
          ElMessage.success('告警配置保存成功')
        }
      }
    }

    // 保存系统配置
    const saveSystemConfig = async () => {
      if (!systemFormRef.value) return
      
      try {
        await systemFormRef.value.validate()
        
        // 模拟API调用
        await api.system.updateSystemConfig({ system: systemConfig })
        
        ElMessage.success('系统配置保存成功')
      } catch (error) {
        if (error !== false) { // 不是表单验证错误
          // 模拟成功
          ElMessage.success('系统配置保存成功')
        }
      }
    }

    // 重置检测配置
    const resetDetectionConfig = () => {
      if (!detectionFormRef.value) return
      detectionFormRef.value.resetFields()
    }

    // 重置告警配置
    const resetAlertConfig = () => {
      if (!alertFormRef.value) return
      alertFormRef.value.resetFields()
    }

    // 重置系统配置
    const resetSystemConfig = () => {
      if (!systemFormRef.value) return
      systemFormRef.value.resetFields()
    }

    // 处理声音文件选择
    const handleSoundFileChange = (file) => {
      alertConfig.sound_file = file.name
    }

    // 导出配置
    const exportConfig = () => {
      ElMessageBox.confirm('确定要导出系统配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 模拟导出
        ElMessage.success('配置导出成功')
      }).catch(() => {})
    }

    // 备份数据
    const backupData = () => {
      ElMessageBox.confirm('确定要备份系统数据吗？此操作可能需要一些时间。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟备份
        ElMessage.success('数据备份成功')
      }).catch(() => {})
    }

    // 初始化
    onMounted(() => {
      fetchSystemConfig()
    })

    return {
      activeTab,
      detectionFormRef,
      alertFormRef,
      systemFormRef,
      detectionConfig,
      alertConfig,
      systemConfig,
      detectionRules,
      alertRules,
      systemRules,
      saveDetectionConfig,
      saveAlertConfig,
      saveSystemConfig,
      resetDetectionConfig,
      resetAlertConfig,
      resetSystemConfig,
      handleSoundFileChange,
      exportConfig,
      backupData
    }
  }
}
</script>

<style scoped>
.system-settings-container {
  padding: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settings-tabs {
  margin-top: 20px;
}

.settings-form {
  padding: 20px 0;
}

.el-form-item {
  margin-bottom: 25px;
}

.file-name {
  margin-left: 10px;
  color: #606266;
}

/* 关于系统样式 */
.about-container {
  padding: 30px 0;
}

.about-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-container {
  width: 100px;
  height: 100px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
}

.logo-icon {
  font-size: 50px;
  color: white;
}

.about-header h1 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 28px;
}

.version {
  color: #606266;
  font-size: 16px;
}

.about-info {
  margin-bottom: 40px;
}

.about-features, .about-tech {
  margin-bottom: 30px;
}

.about-features h3, .about-tech h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 18px;
}

.about-features ul {
  padding-left: 20px;
}

.about-features li {
  margin-bottom: 10px;
  color: #606266;
}

.tech-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>